// 这个文件，专门处理书籍相关的接口

// 1、加载express
// 2、创建路由对象
// 3、把接口挂载到路由对象上
// 4、导出路由对象
// 5、app.js 中，加载模块，并注册成中间件
const path = require('path');
const db = require(path.join(__dirname, '../db'));
const express = require('express');
const router = express.Router();

// 获取所有的书籍接口
router.get('/getbooks', async (req, res) => {
    let r1 = await db('select * from books where id>?', 2);
    let r2 = await db('select count(*) total from books');
    res.send({
        status: 200,
        msg: '获取成功',
        data: r1,
        total: r2[0].total
    });
});

// 添加书籍的接口
router.post('/addbook', async (req, res) => {
    // console.log(req.body);
    let r = await db('insert into books set ?', req.body);
    res.send({status: 201, msg: '添加成功'});
});

// 删除书籍接口
router.get('/delbook', (req, res) => {
    // 获取客户端的请求参数id
    let id = req.query.id;
    // console.log(id);
    let r = db('delete from books where id=?', id);
    res.send({status: 200, msg: '删除成功'});
});

module.exports = router;